package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.constant.Constant;
import com.koocloud.electroplatemanage.mapper.IncomePartUnitMapper;
import com.koocloud.electroplatemanage.pojo.CodeNameResult;
import com.koocloud.electroplatemanage.pojo.DrawNoVo;
import com.koocloud.electroplatemanage.pojo.IncomePartUnitVo;
import com.koocloud.electroplatemanage.pojo.WorkTimeVo;
import com.koocloud.electroplatemanage.service.IncomePartUnitService;
import com.koocloud.electroplatemanage.utils.SecondCheck;
import com.koocloud.electroplatemanage.utils.UUIDUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.*;
import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.ZERO;

/**
 * @program: electroplatemanage
 * @description: 来件单位服务层实现类
 * @author: zww
 * @create: 2020-10-08 17:25
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class IncomePartUnitServiceImpl implements IncomePartUnitService {
    @Resource
    private IncomePartUnitMapper incomePartUnitMapper;
    Lock lock=new ReentrantLock();
    /**
     *@Description:通过pk查询一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate selectByPk(String pk) {
        try {
            //新建来件单位实体
            IncomePartUnitVo incomePartUnitVo = null;
            incomePartUnitVo = incomePartUnitMapper.selectByPk(pk);
            //判断查表操作是否成功
            if (null != incomePartUnitVo) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(incomePartUnitVo).build();
            }
            else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }
    /**
     *@Description:查询所有记录 分页  地址  联系方式
     *@Param: [page, limit,address,contactInformation]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit,IncomePartUnitVo incomePartUnitVo) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                List<IncomePartUnitVo> IncomePartUnitVoList = new ArrayList<>();
                //判断模糊查询是否为状态查询 启用为 1 禁用为 0
                if (!StringUtils.isEmpty(incomePartUnitVo.getIdOrName())){
                    //启用
                    if (STARTUSING.equals(incomePartUnitVo.getIdOrName())){
                        incomePartUnitVo.setIdOrName(ONE);
                        IncomePartUnitVoList = incomePartUnitMapper.selectByDeleteFlag(incomePartUnitVo);
                    //禁用
                    } else if (FORBIDDEN.equals(incomePartUnitVo.getIdOrName())){
                        incomePartUnitVo.setIdOrName(ZERO);
                        IncomePartUnitVoList = incomePartUnitMapper.selectByDeleteFlag(incomePartUnitVo);
                    //模糊查询
                    }else {
                        IncomePartUnitVoList = incomePartUnitMapper.selectAllData(incomePartUnitVo);
                    }
                }else {
                    //全局查询
                    IncomePartUnitVoList = incomePartUnitMapper.selectAllData(incomePartUnitVo);
                }
                //构造分页实体
                PageInfo<IncomePartUnitVo> info=new PageInfo<>(IncomePartUnitVoList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description://插入一条记录
     *@Param: [incomePartUnitVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate insert(IncomePartUnitVo incomePartUnitVo) {
/*        //校验来件单位编码
        if(!StringUtils.isEmpty(incomePartUnitVo.getIncomepartunitCode())&& SecondCheck.codeCheck(incomePartUnitVo.getIncomepartunitCode())) {*/
        try {
            lock.lock();
            //查询来件单位是否存在
            IncomePartUnitVo incomePartUnitVoByCnName = incomePartUnitMapper.selectByCnName(incomePartUnitVo.getCnName());
            if (!StringUtils.isEmpty(incomePartUnitVoByCnName)){
                return ResponseTemplate.builder().code(1).message("该来件单位已存在，或重名！").count(0l).build();
            }else {
                //查询来件单位表中总数
                int sum = incomePartUnitMapper.selectAmount();
                //获取编号字母的字母下标
                int letterGroup = sum / AMOUNT;
                //获取编号数字
                int numberGroup = sum % AMOUNT;
                String str = null;
                //字母数组
                char[] letters = LETTER.toCharArray();
                //判断表中数据为空时和编号数字在0到999之间
                if ((letterGroup == 0 && numberGroup == 0) || (numberGroup > 0 && numberGroup < AMOUNT)) {
                    str = letters[letterGroup] + String.format("%03d", numberGroup + 1);
                } else {
                    str = letters[letterGroup + 1] + String.format("%03d", 1);
                }
                //判断生成的编码是否存在
                while (true) {
                    IncomePartUnitVo incomePartUnitVoByCode = incomePartUnitMapper.selectByCode(str);
                    //存在跳过，继续生成
                    if (!StringUtils.isEmpty(incomePartUnitVoByCode)) {
                        //字母
                        String startStr = null;
                        //数字
                        String endStr = null;
                        startStr = str.substring(0, 1);
                        endStr = str.substring(1);
                        if (Integer.valueOf(endStr) == AMOUNT) {
                            endStr = String.format("%03d", 1);
                            if (startStr.equals(letters[letterGroup])) {
                                startStr = String.valueOf(letters[letterGroup + 1]);
                            } else {
                                startStr = String.valueOf(letters[letterGroup + 2]);
                            }
                            str = startStr + endStr;
                        } else {
                            endStr = String.format("%03d", Integer.valueOf(endStr) + 1);
                            str = startStr + endStr;
                        }
                    } else {
                        break;
                    }
                }
                incomePartUnitVo.setIncomepartunitCode(str);
            }
            //存入来件单位表
            int rows = incomePartUnitMapper.insert(incomePartUnitVo);
            if (rows > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
/*        }
        else {
            return ResponseTemplate.builder().code(1).message("来件单位编码必须大写字母开头,其余为数字，长度为4位").count(0l).build();
        }*/
    }

    /**
     *@Description:批量插入记录
     *@Param: [listIncomePartUnitVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate batchInsert(List<IncomePartUnitVo> listIncomePartUnitVo) {
        if(!listIncomePartUnitVo.isEmpty()) {
            try {
                lock.lock();
                //没有异常并且插入数据条数大于0
                int rows = incomePartUnitMapper.batchInsert(listIncomePartUnitVo);
                if (rows > 0) {
                    return ResponseTemplate.builder().code(0).message("批量插入数据成功").count((long)rows).build();
                } else {//没有异常并且插入数据失败，原则上不出现
                    return ResponseTemplate.builder().code(1).message("批量插入数据失败").count(0l).build();
                }
            } catch (Exception e) {
                //出现异常返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
            finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("传入参数为空").count(0l).build();
        }
    }
    /**
     *@Description:逻辑删除一条记录
     *@Param: [pk]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate delete(String pk,String deleteFlag) {

        try {
            lock.lock();
            int rows = incomePartUnitMapper.delete(pk,deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            }
            else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }
    /**
     *@Description:通过pks批量逻辑删除记录
     *@Param: [listPks]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate batchDeleteByPks(List<String> listPks) {
        if(!listPks.isEmpty()) {
            try {
                lock.lock();
                //存在合法pk值，进行批量删除操作
                int rows = incomePartUnitMapper.batchDeleteByPks(listPks);
                //判断批量删除操作是否成功
                if (rows > 0) {
                    //批量删除成功返回数据
                    return ResponseTemplate.builder().code(0).message("批量删除成功").count((long)rows).build();
                } else {
                    //批量删除失败返回提示
                    return ResponseTemplate.builder().code(1).message("批量删除失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
            finally {
                lock.unlock();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("传入参数为空").count(0l).build();
        }
    }
    /**
     *@Description:修改一条记录
     *@Param: [incomePartUnitVo]
     *@return: com.koocloud.electroplatemanage.common.ResponseTemplate
     *@Author: zww
     *@date: 2020/10/08
     */
    @Override
    public ResponseTemplate update(IncomePartUnitVo incomePartUnitVo) {
        try {
            lock.lock();
            //没有异常并且修改数据条数大于0
            int rows = incomePartUnitMapper.update(incomePartUnitVo);
            if(rows>0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
        finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 校验填写的来件单位表主键
     *@Param: [incomePartUnitVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/10/16
     */
    @Override
    public ResponseTemplate check(IncomePartUnitVo incomePartUnitVo) {
        try {
            log("传入填写的来件单位表主键："+incomePartUnitVo.getIncomepartunitCode());

            if (!StringUtils.isEmpty(incomePartUnitVo.getIncomepartunitCode())){ //判断传入的主键是否为空
                //校验主键的长度
                if (!(incomePartUnitVo.getIncomepartunitCode().length()==Integer.parseInt(Constant.controlPrikeyLength))){

                    return ResponseTemplate.builder().code(1).message("填写的来件单位表主键必须长度为"+Constant.controlPrikeyLength+"位").count(0l).build();
                }else { //校验长度通过
                    if (SecondCheck.codeCheck(incomePartUnitVo.getIncomepartunitCode())) {
                        //根据主键id查询一条数据
                        IncomePartUnitVo incomePartUnitVo1 = incomePartUnitMapper.selectByPk(incomePartUnitVo.getIncomepartunitCode());
                        if (!StringUtils.isEmpty(incomePartUnitVo1)){
                            return ResponseTemplate.builder().code(1).message("填写的来件单位表主键已存在,请重新输入").count(1l).build();
                        }else {
                            return ResponseTemplate.builder().code(0).message("此来件单位表主键可用").count(1l).build();
                        }
                    }else {
                        return ResponseTemplate.builder().code(1).message("来件单位编码必须以大写字母开头，其余为数字，长度为4位。").count(0l).build();
                    }
                }
            }else {
                return ResponseTemplate.builder().code(1).message("传入的来件单位表主键为空").count(1l).build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.toString()).count(0l).build();
        }

    }

    /**
     *@Description: 来件单位编码和名称
     *@Param: []
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/10/19
     */
    @Override
    public ResponseTemplate selectUnit(String idOrName) {

        try {
            List<CodeNameResult> list = incomePartUnitMapper.selectUnit(idOrName);
            //判断查表操作是否成功
            if (list.size()>0) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(list).build();
            }
            else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }

    }


    public void  log(String str){
        System.out.println("====================>"+str+"=================>");
    }
}